package com.yanqu.road.dataHelper.manager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.db.DbParameter;
import com.yanqu.road.dao.impl.logic.DbInfoParser;
import com.yanqu.road.dao.impl.logic.ProcessInfoParser;
import com.yanqu.road.dataHelper.action.excel.ZhouNianQingRankData;
import com.yanqu.road.dataHelper.action.zhounianqing.BanquetCount;
import com.yanqu.road.entity.activity.ActivityConditionInfo;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.UnionActivityConditionData;
import com.yanqu.road.entity.activity.UserActivityConditionData;
import com.yanqu.road.entity.player.CrossUserBaseInfo;
import com.yanqu.road.entity.player.OpenInvitedData;
import com.yanqu.road.entity.player.PlatformUserPotential;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.rank.cross.CrossUnionActivityRank;
import com.yanqu.road.entity.servercenter.CrossServerInfo;
import com.yanqu.road.entity.servercenter.DbInfo;
import com.yanqu.road.entity.servercenter.ProcessInfo;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.entity.union.UnionConstruct;
import com.yanqu.road.entity.union.cross.*;
import com.yanqu.road.entity.union.parergon.UnionBussinessman;
import com.yanqu.road.entity.union.parergon.UnionBussinessmanDetail;
import com.yanqu.road.entity.union.parergon.UnionParergon;
import com.yanqu.road.entity.union.parergon.UnionParergonPlayer;
import com.yanqu.road.entity.union.trade.UnionTradeTeamData;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.sql.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class ServerMgr extends BaseMgr {

    static Map<Long, ServerInfo> serverInfoList = new ConcurrentHashMap<>();
    static Map<Long, DbInfo> dbInfoMap = new ConcurrentHashMap<>();

    static Map<Long, DbInfo> dbLogInfoMap = new ConcurrentHashMap<>();

    static Map<Long, DbInfo> dbCrossInfoMap = new ConcurrentHashMap<>();
    static boolean isInit;
    public ServerMgr() {
        init();
    }

    public  List<PlatformUserPotential> selectAllPotential() {
        List<PlatformUserPotential> list = new ArrayList<>();
        ResultSet rs = null;
        CallableStatement call = null;
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall("select * from t_s_user_potential ");
            rs = call.executeQuery();
            while (rs.next()) {
                String platformUserId = rs.getString("platformUserId");
                int potential = rs.getInt("potential");
                PlatformUserPotential platformUserPotential = new PlatformUserPotential();
                platformUserPotential.setPlatformUserId(platformUserId);
                platformUserPotential.setPotential(potential);
                list.add(platformUserPotential);
            }
        } catch (SQLException e) {
            logger.error("异常错误", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return list;
    }


    public List<OpenInvitedData> selectAllInvitedData() {
        List<OpenInvitedData> list = new ArrayList<>();
        ResultSet rs = null;
        CallableStatement call = null;
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall("select * from t_s_open_invited_data ");
            rs = call.executeQuery();
            while (rs.next()) {
                OpenInvitedData openInvitedData = new OpenInvitedData();
                openInvitedData.setOpenId(rs.getString("openId"));
                openInvitedData.setInvitedCode(rs.getString("invitedCode"));
                openInvitedData.setRegisterTime(rs.getLong("registerTime"));
                list.add(openInvitedData);
            }
        } catch (SQLException e) {
            logger.error("异常错误", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return list;
    }

    private void init() {
        synchronized (ServerMgr.class) {
            if (isInit) {
                return;
            }
            initServer();
            initUserDb();
            initCrossDb();
            initLogDb();
            isInit = true;
        }
    }

    public static Map<Long, ServerInfo> getServerInfoList() {
        return serverInfoList;
    }

    public static Map<Long, DbInfo> getDbInfoMap() {
        return dbInfoMap;
    }

    public static Map<Long, DbInfo> getLogDbInfoMap() {
        return dbLogInfoMap;
    }

    public static Map<Long, DbInfo> getDbCrossInfoMap() {
        return dbCrossInfoMap;
    }

    public List<Long> getWhereServer(String whereServeer) {
        List<Long> serverIdList = new ArrayList<>();
        ResultSet rs = null;
        CallableStatement call = null;
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall("select * from t_s_server_list where " + whereServeer);
            rs = call.executeQuery();
            while (rs.next()) {
                serverIdList.add(rs.getLong("serverId"));
            }
        } catch (SQLException e) {
            logger.error("异常错误", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return serverIdList;
    }

    private void initServer() {
        ResultSet rs = null;
        CallableStatement call = null;
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall("select * from t_s_server_list");
            rs = call.executeQuery();
            while (rs.next()) {
                ServerInfo serverInfo = new ServerInfo();
                serverInfo.setServerId(rs.getLong("serverId"));
                serverInfo.setServerName(rs.getString("serverName"));
                serverInfo.setGameServerUrl(rs.getString("gameServerUrl"));
                serverInfo.setDbIndex(rs.getString("dbIndex"));
                serverInfo.setOpenTime(rs.getInt("openTime"));
                serverInfoList.put(serverInfo.getServerId(), serverInfo);
            }
        } catch (SQLException e) {
            logger.error("异常错误", e);
        } finally {
            getDb().closeConnection(call, null);
        }
    }

    public void initUserDb() {
        ResultSet rs = null;
        CallableStatement call = null;
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall("select serverId, userDataBase from t_s_db_info");
            rs = call.executeQuery();
            while (rs.next()) {
                long serverId = rs.getLong("serverId");
                String jsStr = rs.getString("userDatabase");

                JSONObject jObject = JSONObject.parseObject(jsStr);
                DbInfo info = new DbInfo();
                info.setDbName(jObject.getString("dbname"));
                info.setUserName(jObject.getString("dbuser"));
                info.setIp(jObject.getString("ip"));
                info.setPassword(jObject.getString("dbpassword"));
                info.setPort(Integer.valueOf(jObject.getString("port")));
                dbInfoMap.put(serverId, info);
            }
        } catch (SQLException e) {
            logger.error("异常错误", e);
        } finally {
            getDb().closeConnection(call, null);
        }
    }

    public void initCrossDb() {
        ResultSet rs = null;
        CallableStatement call = null;
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall("select * from t_s_cross_server_list");
            rs = call.executeQuery();
            while (rs.next()) {
                long serverId = rs.getLong("crossServerId");
                String jsStr = rs.getString("crossDatabase");

                JSONObject jObject = JSONObject.parseObject(jsStr);
                DbInfo info = new DbInfo();
                info.setDbName(jObject.getString("dbname"));
                info.setUserName(jObject.getString("dbuser"));
                info.setIp(jObject.getString("ip"));
                info.setPassword(jObject.getString("dbpassword"));
                info.setPort(Integer.valueOf(jObject.getString("port")));
                dbCrossInfoMap.put(serverId, info);
            }
        } catch (SQLException e) {
            logger.error("异常错误", e);
        } finally {
            getDb().closeConnection(call, null);
        }
    }

    public void initLogDb() {
        ResultSet rs = null;
        CallableStatement call = null;
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall("select serverId, logDatabase from t_s_db_info");
            rs = call.executeQuery();
            while (rs.next()) {
                long serverId = rs.getLong("serverId");
                String jsStr = rs.getString("logDatabase");

                JSONObject jObject = JSONObject.parseObject(jsStr);
                DbInfo info = new DbInfo();
                info.setDbName(jObject.getString("dbname"));
                info.setUserName(jObject.getString("dbuser"));
                info.setIp(jObject.getString("ip"));
                info.setPassword(jObject.getString("dbpassword"));
                info.setPort(Integer.valueOf(jObject.getString("port")));
                dbLogInfoMap.put(serverId, info);
            }
        } catch (SQLException e) {
            logger.error("异常错误", e);
        } finally {
            getDb().closeConnection(call, null);
        }
    }

    public void insetRebate(List<Map<String, String>> list) {
        boolean result = false;
        String sql = "INSERT INTO t_s_rebate_cn" +
                " (userCount,userId,openId,platformUserId,vipExp,buySecret,buyFund,buyYear,buyMonth,isRebate) " +
                " VALUES(?,?,?,?,?,?,?,?,?,?)";
        List<Map<Integer, DbParameter>> mapList = new ArrayList<>();
        for (Map<String, String> data : list) {
            Map<Integer, DbParameter> para = new HashMap<>();
            int i = 1;
            para.put(i++, new DbParameter(Types.VARCHAR, data.get("userCount")));
            para.put(i++, new DbParameter(Types.VARCHAR, data.get("userId")));
            para.put(i++, new DbParameter(Types.VARCHAR, data.get("openId")));
            para.put(i++, new DbParameter(Types.VARCHAR, data.get("platformUserId")));
            para.put(i++, new DbParameter(Types.VARCHAR, data.get("vipExp")));
            para.put(i++, new DbParameter(Types.VARCHAR, data.get("buySecret")));
            para.put(i++, new DbParameter(Types.VARCHAR, data.get("buyFund")));
            para.put(i++, new DbParameter(Types.VARCHAR, data.get("buyYear")));
            para.put(i++, new DbParameter(Types.VARCHAR, data.get("buyMonth")));
            para.put(i++, new DbParameter(Types.INTEGER, 0));
            mapList.add(para);
        }

        if (getDb().executeBatchQuery(sql, mapList) > -1) {
            result = true;
        }
    }

    public Map<Integer, ActivityInfo> getActivityInfoBy(int type, int childType, int type2, int childType2, long serverId, String beginTimeStr, String endTimeStr) {
        Map<Integer, ActivityInfo> dataMap = new HashMap<>();
        ResultSet rs = null;
        CallableStatement call = null;
        String activityIdCondition = " ((type = " + type + " and childType = " + childType + ")";
        if (type2 > 0) {
            activityIdCondition += "or (" + "type = " + type2 + " and childType = " + childType2 + ")) ";
        }
        String sql = "select activityId,endTime from t_s_activity_main where " + activityIdCondition + "  and serverList like '%" + serverId + "%' and beginShowTime >= ? and endTime < ?";
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall(sql);
            int i = 1;
            call.setString(i++, beginTimeStr);
            call.setString(i++, endTimeStr);
            rs = call.executeQuery();
            while (rs.next()) {
                ActivityInfo activityInfo = new ActivityInfo();
                int activityId = rs.getInt("activityId");
                long endTime = rs.getTimestamp("endTime").getTime() / 1000;
                activityInfo.setActivityId(activityId);
                activityInfo.setEndTime(endTime);
                dataMap.put(activityId, activityInfo);
            }
        } catch (SQLException ex) {
            logger.error("异常错误", ex);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    public Map<Integer, Long> getActivityEndTime(List<Integer> activityList) {
        Map<Integer, Long> dataMap = new HashMap<>();
        ResultSet rs = null;
        CallableStatement call = null;
        String activityIdCondition = "activityId in(" + StringUtils.listToString(activityList, ",") + ")";
        String sql = "select activityId,endTime from t_s_activity_main where " + activityIdCondition;
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall(sql);
            rs = call.executeQuery();
            while (rs.next()) {
                int activityId = rs.getInt("activityId");
                long endTime = rs.getTimestamp("endTime").getTime() / 1000;
                dataMap.put(activityId, endTime);
            }
        } catch (SQLException ex) {
            logger.error("异常错误", ex);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    public Map<Integer, ActivityInfo> getActivityInfoMap(List<Integer> activityList) {
        Map<Integer, ActivityInfo> dataMap = new HashMap<>();
        if(null == activityList || activityList.size() <= 0){
            return dataMap;
        }
        ResultSet rs = null;
        CallableStatement call = null;
        String activityIdCondition = "activityId in(" + StringUtils.listToString(activityList, ",") + ")";
        String sql = "select * from t_s_activity_main where " + activityIdCondition;
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall(sql);
            rs = call.executeQuery();
            while (rs.next()) {
                ActivityInfo activityInfo = new ActivityInfo();
                int activityId = rs.getInt("activityId");
                long endTime = rs.getTimestamp("endTime").getTime() / 1000;
                activityInfo.setActivityId(activityId);
                activityInfo.setEndTime(endTime);
                activityInfo.setType(rs.getInt("type"));
                dataMap.put(activityId, activityInfo);
            }
        } catch (SQLException ex) {
            logger.error("异常错误", ex);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    public List<Integer> getTaskActivityIdList(String endShowTime) {
        List<Integer> dataList = new ArrayList<>();
        ResultSet rs = null;
        CallableStatement call = null;
//        String sql = "select * from t_s_activity_main where type = 3 AND endShowTime<?";
        String sql = "select * from t_s_over_activity";
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall(sql);
            rs = call.executeQuery();
            while (rs.next()) {
                dataList.add(rs.getInt("activityId"));
            }
        } catch (SQLException ex) {
            logger.error("异常错误", ex);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataList;
    }

    public Map<Integer, Long> getActivityEndShowTime(int activityId) {
        Map<Integer, Long> dataMap = new HashMap<>();
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select activityId,endShowTime from t_s_activity_main where activityId = " + activityId;
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall(sql);
            rs = call.executeQuery();
            while (rs.next()) {
                long endTime = rs.getTimestamp("endShowTime").getTime() / 1000;
                dataMap.put(activityId, endTime);
            }
        } catch (SQLException ex) {
            logger.error("异常错误", ex);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    public List<Long> getActivityCrossIdList(List<Integer> activityList){
        List<Long> dataList = new ArrayList<>();
        ResultSet rs = null;
        CallableStatement call = null;
        String activityIdCondition = "activityId in(" + StringUtils.listToString(activityList, ",") + ")";
        String sql = "select activityId,crossServerId from t_s_activity_main where " + activityIdCondition;
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall(sql);
            rs = call.executeQuery();
            while (rs.next()) {
                int activityId = rs.getInt("activityId");
                long crossId = rs.getLong("crossServerId");
                if(!dataList.contains(crossId)){
                    dataList.add(crossId);
                }
            }
        } catch (SQLException ex) {
            logger.error("异常错误", ex);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataList;
    }

    public Map<Integer,List<ActivityConditionInfo>> getRankActivityRewardList(List<Integer> activityList){
        Map<Integer,List<ActivityConditionInfo>> dataList = new ConcurrentHashMap<>();
        ResultSet rs = null;
        CallableStatement call = null;
        String activityIdCondition = "activityId in(" + StringUtils.listToString(activityList, ",") + ")";
        String sql = "select activityId,rewards,masterRewards,params from t_s_activity_condition where `type` = 2 AND " + activityIdCondition;
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall(sql);
            rs = call.executeQuery();
            while (rs.next()) {
                ActivityConditionInfo activityConditionInfo = new ActivityConditionInfo();
                activityConditionInfo.setActivityId(rs.getInt("activityId"));
                activityConditionInfo.setParamList(StringUtils.stringToBigIntegerList(rs.getString("params"),"\\|"));
                activityConditionInfo.setReward(PropertyHelper.parseStringToProperty(rs.getString("rewards")));
                activityConditionInfo.setMasterReward(PropertyHelper.parseStringToProperty(rs.getString("masterRewards")));
                if(!dataList.containsKey(activityConditionInfo.getActivityId())){
                    dataList.put(activityConditionInfo.getActivityId(),new ArrayList<>());
                }
                dataList.get(activityConditionInfo.getActivityId()).add(activityConditionInfo);
            }
        } catch (SQLException ex) {
            logger.error("异常错误", ex);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataList;
    }

    public List<CrossServerInfo> getCrossServerInfoList(List<Long> crossIdList){
        ResultSet rs = null;
        CallableStatement call = null;
        List<CrossServerInfo> list = new ArrayList<>();
        if(crossIdList.size() == 0){
            return list;
        }
        String condition = "crossServerId in(" + StringUtils.listToString(crossIdList, ",") + ")";
        String sql = "select * from t_s_cross_server_list WHERE " + condition;
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall(sql);
            rs = call.executeQuery();
            while (rs.next()) {
                CrossServerInfo crossServerInfo = new CrossServerInfo();
                int crossServerId = rs.getInt("crossServerId");
                crossServerInfo.setCrossServerId(rs.getInt("crossServerId"));
                DbInfo dbInfo = DbInfoParser.parseDbInfo(rs.getString("crossDatabase"));
                if (dbInfo != null) {
                    crossServerInfo.getDbInfos().add(dbInfo);
                }
                DbInfo configbase = DbInfoParser.parseDbInfo(rs.getString("crossConfigbase"));
                if (configbase != null) {
                    crossServerInfo.getDbInfos().add(configbase);
                }

                ProcessInfo crossProcessInfo = ProcessInfoParser.parsingProcessInfo(rs.getString("crossServerInfo"), crossServerId);
                ProcessInfo webServerInfo = ProcessInfoParser.parsingProcessInfo(rs.getString("webServerInfo"), crossServerId);
                crossServerInfo.getProcessInfoList().add(crossProcessInfo);
                crossServerInfo.getProcessInfoList().add(webServerInfo);
                crossServerInfo.setCrossServerType(rs.getInt("crossServerType"));
                list.add(crossServerInfo);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return list;
    }

    private CrossServerInfo parseCrossServerInfo(int crossServerId, ResultSet rs) throws SQLException {
        CrossServerInfo crossServerInfo = new CrossServerInfo();
        crossServerInfo.setCrossServerId(crossServerId);
        DbInfo dbInfo = DbInfoParser.parseDbInfo(rs.getString("crossDatabase"));
        if (dbInfo != null) {
            crossServerInfo.getDbInfos().add(dbInfo);
        }
        DbInfo configbase = DbInfoParser.parseDbInfo(rs.getString("crossConfigbase"));
        if (configbase != null) {
            crossServerInfo.getDbInfos().add(configbase);
        }

        ProcessInfo crossProcessInfo = ProcessInfoParser.parsingProcessInfo(rs.getString("crossServerInfo"), crossServerId);
        ProcessInfo webServerInfo = ProcessInfoParser.parsingProcessInfo(rs.getString("webServerInfo"), crossServerId);
        crossServerInfo.getProcessInfoList().add(crossProcessInfo);
        crossServerInfo.getProcessInfoList().add(webServerInfo);
        crossServerInfo.setCrossServerType(rs.getInt("crossServerType"));
        return crossServerInfo;
    }

    //统计玩家跨服库-宴会人气/场次（按区服）
    public Map<Long, List<BanquetCount>> getCrossBanquet(long userId, long beginTime, long endTime) {
        Map<Long, List<BanquetCount>> dataMap = new HashMap<>();
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select userId,type,sum(popularity) as total,count(type) as count0 " +
                "from t_c_banquet where userId = ? and openTime >= ? and openTime < ? " +
                " group by type ";
        try {
            int i = 1;
            getDb().setConnName(DbNameStrategy.getCrossDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setLong(i++, userId);
            call.setLong(i++, beginTime);
            call.setLong(i++, endTime);
            rs = call.executeQuery();
            while (rs.next()) {
                long uid = rs.getLong("userId");
                int type = rs.getInt("type");
                int count = rs.getInt("count0");
                int total = rs.getInt("total");
                BanquetCount banquetCount = new BanquetCount(uid, type, count, total);
                if (!dataMap.containsKey(uid)) {
                    dataMap.put(uid, new ArrayList<>());
                }
                dataMap.get(uid).add(banquetCount);
            }
        } catch (SQLException ex) {
            logger.error("异常错误", ex);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    //统计玩家跨服库私宴-宴会人气/场次（按区服）
    public Map<Long, List<BanquetCount>> getCrossBanquetPersonal(long userId, long beginTime, long endTime) {
        Map<Long, List<BanquetCount>> dataMap = new HashMap<>();
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select userId,type,sum(popularity) as total,count(type) as count0 " +
                "from t_c_banquet_personal where userId = ? and openTime >= ? and openTime < ? " +
                " group by type";
        try {
            int i = 1;
            getDb().setConnName(DbNameStrategy.getCrossDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setLong(i++, userId);
            call.setLong(i++, beginTime);
            call.setLong(i++, endTime);
            rs = call.executeQuery();
            while (rs.next()) {
                long uid = rs.getLong("userId");
                int type = rs.getInt("type");
                int count = rs.getInt("count0");
                int total = rs.getInt("total");
                BanquetCount banquetCount = new BanquetCount(uid, type, count, total);
                if (!dataMap.containsKey(uid)) {
                    dataMap.put(uid, new ArrayList<>());
                }
                dataMap.get(uid).add(banquetCount);
            }
        } catch (SQLException ex) {
            logger.error("异常错误", ex);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }


    public static String insertMammonHallSourceDataInfoSql = "insert into `t_c_activity_mammon_hall_source`(userId,serverId,type,activityId,dataTime,rank,value,otherString,kvList) values (?,?,?,?,?,?,?,?,?)";

    public boolean addRankData(List<ZhouNianQingRankData> dataInfoList) {
        getDb().setConnName(DbNameStrategy.getCrossDb());
        for (int k = 0; k < dataInfoList.size(); k++) {
            ZhouNianQingRankData dataInfo = dataInfoList.get(k);
            int i = 1;
            Map<Integer, DbParameter> para = new HashMap<Integer, DbParameter>();
            para.put(i++, new DbParameter(Types.BIGINT, dataInfo.getUserId()));
            para.put(i++, new DbParameter(Types.BIGINT, dataInfo.getServerId()));
            para.put(i++, new DbParameter(Types.INTEGER, dataInfo.getType()));
            para.put(i++, new DbParameter(Types.INTEGER, dataInfo.getActivityId()));
            para.put(i++, new DbParameter(Types.INTEGER, (int) dataInfo.getDataTime()));
            para.put(i++, new DbParameter(Types.INTEGER, k + 1));
            para.put(i++, new DbParameter(Types.VARCHAR, dataInfo.getValue()));
            para.put(i++, new DbParameter(Types.VARCHAR, dataInfo.getOtherValue()));
            para.put(i++, new DbParameter(Types.VARCHAR, dataInfo.getKv()));
            if (getDb().executeNoneQuery(insertMammonHallSourceDataInfoSql, para) > 0) {
                continue;
            } else {
                return false;
            }
        }
        return true;
    }

    public static String insertMammonHallSourceDataInfoSql2 = "insert into `t_c_activity_mammon_hall_source`(userId,serverId,type,activityId,dataTime,rank,value,otherString,kvList) values (?,?,?,?,?,?,?,?,?)";

    public boolean addRankData2(List<ZhouNianQingRankData> dataInfoList) {
        getDb().setConnName(DbNameStrategy.getCrossDb() + 2);
        for (int k = 0; k < dataInfoList.size(); k++) {
            ZhouNianQingRankData dataInfo = dataInfoList.get(k);
            int i = 1;
            Map<Integer, DbParameter> para = new HashMap<Integer, DbParameter>();
            para.put(i++, new DbParameter(Types.BIGINT, dataInfo.getUserId()));
            para.put(i++, new DbParameter(Types.BIGINT, dataInfo.getServerId()));
            para.put(i++, new DbParameter(Types.INTEGER, dataInfo.getType()));
            para.put(i++, new DbParameter(Types.INTEGER, dataInfo.getActivityId()));
            para.put(i++, new DbParameter(Types.INTEGER, (int) dataInfo.getDataTime()));
            para.put(i++, new DbParameter(Types.INTEGER, k + 1));
            para.put(i++, new DbParameter(Types.VARCHAR, dataInfo.getValue()));
            para.put(i++, new DbParameter(Types.VARCHAR, dataInfo.getOtherValue()));
            para.put(i++, new DbParameter(Types.VARCHAR, dataInfo.getKv()));
            if (getDb().executeNoneQuery(insertMammonHallSourceDataInfoSql, para) > 0) {
                continue;
            } else {
                return false;
            }
        }
        return true;
    }


    public List<CrossUserBaseInfo> getFromCross() {
        String insertMammonHallSourceDataInfoSql2 = "select * from t_c_user_base_info";
        List<CrossUserBaseInfo> dataMap = new ArrayList<>();
        ResultSet rs = null;
        CallableStatement call = null;
        try {
            int i = 1;
            getDb().setConnName(DbNameStrategy.getCrossDb());
            call = getDb().getConnection().prepareCall(insertMammonHallSourceDataInfoSql2);
            rs = call.executeQuery();
            while (rs.next()) {
                long uid = rs.getLong("userId");
                long count = rs.getLong("lastUpdateTime");
                CrossUserBaseInfo info = new CrossUserBaseInfo();
                info.setUserId(uid);
                info.setUserBaseInfo(JSON.parseObject(rs.getString("userBaseInfo"), new TypeReference<UserBaseInfo>() {
                }));
                info.setLastUpdateTime(count);
                dataMap.add(info);
            }
        } catch (SQLException ex) {
            logger.error("异常错误", ex);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    public void insertUserBaseInfo(CrossUserBaseInfo data) {
        String sql = "REPLACE INTO t_c_user_base_info(userId,userBaseInfo,lastUpdateTime) VALUES(?,?,?)";
        try {
            List<Map<Integer, DbParameter>> mapList = new ArrayList<>();
            getDb().setConnName(DbNameStrategy.getCrossDb() + 2);
            int i = 1;
            Map<Integer, DbParameter> para = new HashMap<>();
            para.put(i++, new DbParameter(Types.BIGINT, data.getUserId()));
            para.put(i++, new DbParameter(Types.NVARCHAR, JSON.toJSONString(data.getUserBaseInfo())));
            para.put(i++, new DbParameter(Types.BIGINT, data.getLastUpdateTime()));
            mapList.add(para);
            if (getDb().executeBatchQuery(sql, mapList) > -1) {
            }
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        }
    }

    public boolean addUserConditionData(UserActivityConditionData data, CrossServerInfo crossServerInfo) {
        PreparedStatement call = null;
        Connection conn = null;
        String sql = "insert into t_c_activity_condition(userId,activityId,conditionId,preValue,value,isGetReward,modifyTime,param," +
                "type) values (?,?,?,?,?,?,?,?,?)";
        try {
            conn = getConnect(crossServerInfo.getDbInfos().get(0));
            call = conn.prepareStatement(sql);
            int i = 1;
            call.setLong(i++, data.getUserId());
            call.setInt(i++, data.getActivityId());
            call.setInt(i++, data.getConditionId());
            call.setString(i++, data.getPreValue().toString());
            call.setString(i++, data.getValue().toString());
            call.setBoolean(i++, data.isGetReward());
            call.setLong(i++, data.getModifyTime());
            call.setString(i++, data.getParam());
            call.setInt(i++, data.getType());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            if (call != null) {
                try {
                    call.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    public boolean addCrossUnionInfoList(List<CrossUnionInfo> dataList) {
        String sql = "INSERT INTO t_c_union(unionUid,unionName,createTime,outNotice,innerNotice,experience,ownerUserId,ownerNickName,ownerJoinTime,wechatCode,"
                + "qqCode,memberCount,isAllowRandomJoin,totalEarnSpeed,wealth,isDelete,constructUserIdList,modifyTime,unionFightRewardMark,unionFlag,"
                + "flagModifyTime,constructActive,vipExp,unionAliasId,decoration,rankActivityId,rankAddExp,preUnionFlag,dayJoinNum,serverId,`cross`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

        try {
            getDb().setConnName(DbNameStrategy.getCross2Db());
            List<Map<Integer, DbParameter>> mapList = new ArrayList<>();
            for (CrossUnionInfo data : dataList) {
                Map<Integer, DbParameter> para = new HashMap<>();
                int i = 1;
                para.put(i++, new DbParameter(Types.VARCHAR, data.getUnionUid()));
                para.put(i++, new DbParameter(Types.VARCHAR, data.getUnionName()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getCreateTime()));
                para.put(i++, new DbParameter(Types.VARCHAR, data.getOutNotice()));
                para.put(i++, new DbParameter(Types.VARCHAR, data.getInnerNotice()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getExperience()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getMasterUserId()));
                para.put(i++, new DbParameter(Types.VARCHAR, data.getMasterNickName()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getMasterJoinTime()));
                para.put(i++, new DbParameter(Types.VARCHAR, data.getWechatCode()));
                para.put(i++, new DbParameter(Types.VARCHAR, data.getQqCode()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getMemberCount()));
                para.put(i++, new DbParameter(Types.BOOLEAN, data.isAllowRandomJoin()));
                para.put(i++, new DbParameter(Types.VARCHAR, data.getTotalEarnSpeed().toString()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getWealth()));
                para.put(i++, new DbParameter(Types.BOOLEAN, data.isDelete()));
                para.put(i++, new DbParameter(Types.VARCHAR, data.getConstructUserIdListString()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getModifyTime()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getUnionFightRewardMark()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getUnionFlag()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getFlagModifyTime()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getConstructActive()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getVipExp()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getUnionAliasId()));
                para.put(i++, new DbParameter(Types.VARCHAR, data.getDecoration()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getRankActivityId()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getRankAddExp()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getPreUnionFlag()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getDayJoinNum()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getServerId()));
                para.put(i++, new DbParameter(Types.BOOLEAN, data.isCross()));

                mapList.add(para);
            }
            return getDb().executeBatchQuery(sql, mapList) > -1;
        }catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        }
        return false;
    }

    public boolean addData(CrossUnionInfo data) {
        PreparedStatement call = null;
        String sql = "INSERT INTO t_c_union(unionUid,unionName,createTime,outNotice,innerNotice,experience,ownerUserId,ownerNickName,ownerJoinTime,wechatCode,"
                + "qqCode,memberCount,isAllowRandomJoin,totalEarnSpeed,wealth,isDelete,constructUserIdList,modifyTime,unionFightRewardMark,unionFlag,"
                + "flagModifyTime,constructActive,vipExp,unionAliasId,decoration,rankActivityId,rankAddExp,preUnionFlag,dayJoinNum,serverId,`cross`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        try {
            getDb().setConnName(DbNameStrategy.getCross2Db());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setString(i++, data.getUnionUid());
            call.setString(i++, data.getUnionName());
            call.setLong(i++, data.getCreateTime());
            call.setString(i++, data.getOutNotice());
            call.setString(i++, data.getInnerNotice());
            call.setLong(i++, data.getExperience());
            call.setLong(i++, data.getMasterUserId());
            call.setString(i++, data.getMasterNickName());
            call.setLong(i++, data.getMasterJoinTime());
            call.setString(i++, data.getWechatCode());
            call.setString(i++, data.getQqCode());
            call.setInt(i++, data.getMemberCount());
            call.setBoolean(i++, data.isAllowRandomJoin());
            call.setString(i++, data.getTotalEarnSpeed().toString());
            call.setLong(i++, data.getWealth());
            call.setBoolean(i++, data.isDelete());
            call.setString(i++, data.getConstructUserIdListString());
            call.setLong(i++, data.getModifyTime());
            call.setInt(i++, data.getUnionFightRewardMark());
            call.setInt(i++, data.getUnionFlag());
            call.setLong(i++, data.getFlagModifyTime());
            call.setInt(i++, data.getConstructActive());
            call.setLong(i++, data.getVipExp());
            call.setLong(i++, data.getUnionAliasId());
            call.setString(i++, data.getDecoration());
            call.setInt(i++, data.getRankActivityId());
            call.setLong(i++, data.getRankAddExp());
            call.setInt(i++, data.getPreUnionFlag());
            call.setInt(i++, data.getDayJoinNum());
            call.setLong(i++, data.getServerId());
            call.setBoolean(i++, data.isCross());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    public List<CrossUnionInfo> getCrossUnionInfo() {
        String insertMammonHallSourceDataInfoSql2 = "select * from t_c_union";
        List<CrossUnionInfo> dataMap = new ArrayList<>();
        ResultSet rs = null;
        CallableStatement call = null;
        try {
            int i = 1;
            getDb().setConnName(DbNameStrategy.getCrossDb());
            call = getDb().getConnection().prepareCall(insertMammonHallSourceDataInfoSql2);
            rs = call.executeQuery();
            while (rs.next()) {
                CrossUnionInfo data = new CrossUnionInfo();
                data.setUnionUid(rs.getString("unionUid"));
                data.setUnionName(rs.getString("unionName"));
                data.setCreateTime(rs.getLong("createTime"));
                data.setOutNotice(rs.getString("outNotice"));
                data.setInnerNotice(rs.getString("innerNotice"));
                data.setExperience(rs.getLong("experience"));
                data.setMasterUserId(rs.getLong("ownerUserId"));
                data.setMasterNickName(rs.getString("ownerNickName"));
                data.setMasterJoinTime(rs.getLong("ownerJoinTime"));
                data.setWechatCode(rs.getString("wechatCode"));
                data.setQqCode(rs.getString("qqCode"));
                data.setMemberCount(rs.getInt("memberCount"));
                data.setAllowRandomJoin(rs.getBoolean("isAllowRandomJoin"));
                String value = rs.getString("totalEarnSpeed");
                if (!StringUtils.isNullOrEmpty(value)) {
                    data.setTotalEarnSpeed(new BigInteger(value));
                }
                data.setWealth(rs.getLong("wealth"));
                data.setDelete(rs.getBoolean("isDelete"));
                data.setModifyTime(rs.getLong("modifyTime"));
                data.setUnionFightRewardMark(rs.getInt("unionFightRewardMark"));
                data.setUnionFlag(rs.getInt("unionFlag"));
                data.setFlagModifyTime(rs.getLong("flagModifyTime"));
                data.setConstructActive(rs.getInt("constructActive"));
                data.setVipExp(rs.getLong("vipExp"));
                data.setConstructUserIdList(StringUtils.stringToLongList(rs.getString("constructUserIdList"), ","));
                data.setUnionAliasId(rs.getLong("unionAliasId"));
                value = rs.getString("decoration");
                if (!StringUtils.isNullOrEmpty(value)) {
                    data.setDecoration(value);
                }
                data.setRankActivityId(rs.getInt("rankActivityId"));
                data.setRankAddExp(rs.getLong("rankAddExp"));
                data.setPreUnionFlag(rs.getInt("preUnionFlag"));
                data.setDayJoinNum(rs.getInt("dayJoinNum"));
                data.setServerId(rs.getLong("serverId"));
                data.setCross(rs.getBoolean("cross"));
                dataMap.add(data);
            }
        } catch (SQLException ex) {
            logger.error("异常错误", ex);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    public boolean addCrossUnionMemberList(List<CrossUnionMember> dataList) {
        String sql = "INSERT INTO t_c_union_member(unionUid,userId,position,userBaseInfo,modifyTime,contribution,totalContribution,"
                + "donateTimes,quitTime,unionConstructData,constructRewardIndexList,todayContribution,chamberPatronsId,serverId) VALUES "
                + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        try {
            getDb().setConnName(DbNameStrategy.getCross2Db());
            List<Map<Integer, DbParameter>> mapList = new ArrayList<>();
            for (CrossUnionMember data : dataList) {
                Map<Integer, DbParameter> para = new HashMap<>();
                int i = 1;
                para.put(i++, new DbParameter(Types.VARCHAR, data.getUnionUid()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getUserId()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getPosition()));
                para.put(i++, new DbParameter(Types.VARCHAR, data.getUserBaseInfoJsonStr()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getModifyTime()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getContribution()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getTotalContribution()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getDonateTimes()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getQuitTime()));
                para.put(i++, new DbParameter(Types.VARCHAR, data.getUnionConstructMapJson()));
                para.put(i++, new DbParameter(Types.VARCHAR, data.getConstructRewardIndexListString()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getTodayContribution()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getChamberPatronsId()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getServerId()));

                mapList.add(para);
            }
            return getDb().executeBatchQuery(sql, mapList) > -1;
        }catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        }
        return false;
    }

    public boolean addData(CrossUnionMember data) {
        PreparedStatement call = null;
        String sql = "INSERT INTO t_c_union_member(unionUid,userId,position,userBaseInfo,modifyTime,contribution,totalContribution,"
                + "donateTimes,quitTime,unionConstructData,constructRewardIndexList,todayContribution,chamberPatronsId,serverId) VALUES "
                + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        try {
            getDb().setConnName(DbNameStrategy.getCross2Db());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setString(i++, data.getUnionUid());
            call.setLong(i++, data.getUserId());
            call.setInt(i++, data.getPosition());
            call.setString(i++, data.getUserBaseInfoJsonStr());
            call.setLong(i++, data.getModifyTime());
            call.setLong(i++, data.getContribution());
            call.setLong(i++, data.getTotalContribution());
            call.setInt(i++, data.getDonateTimes());
            call.setLong(i++, data.getQuitTime());
            call.setString(i++, data.getUnionConstructMapJson());
            call.setString(i++, data.getConstructRewardIndexListString());
            call.setInt(i++, data.getTodayContribution());
            call.setInt(i++, data.getChamberPatronsId());
            call.setLong(i++, data.getServerId());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    public static String insertCrossChamberPatronsSql = "insert into `t_c_union_chamber`(userId,patronsId,skillList,ability,level,stageLv,breakLv,skinId,promotionId) values (?,?,?,?,?,?,?,?,?)";
    public boolean addCrossUnionChamberPatronsList(List<CrossUnionChamberPatrons> dataList) {
        try {
            getDb().setConnName(DbNameStrategy.getCross2Db());
            List<Map<Integer, DbParameter>> mapList = new ArrayList<>();
            for (CrossUnionChamberPatrons data : dataList) {
                Map<Integer, DbParameter> para = new HashMap<>();
                int i = 1;
                para.put(i++, new DbParameter(Types.BIGINT, data.getUserId()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getPatronsId()));
                para.put(i++, new DbParameter(Types.VARCHAR, data.getSkillListStr()));
                para.put(i++, new DbParameter(Types.VARCHAR, data.getAbility().toString()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getLevel()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getStageLv()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getBreakLv()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getSkinId()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getPromotionId()));

                mapList.add(para);
            }
            return getDb().executeBatchQuery(insertCrossChamberPatronsSql, mapList) > -1;
        }catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        }
        return false;
    }
    public boolean addData(CrossUnionChamberPatrons data) {
        data.setBeginWriteTime();
        getDb().setConnName(DbNameStrategy.getCross2Db());
        int i = 1;
        Map<Integer, DbParameter> para = new HashMap<Integer, DbParameter>();
        para.put(i++, new DbParameter(Types.BIGINT, data.getUserId()));
        para.put(i++, new DbParameter(Types.INTEGER, data.getPatronsId()));
        para.put(i++, new DbParameter(Types.VARCHAR, data.getSkillListStr()));
        para.put(i++, new DbParameter(Types.VARCHAR, data.getAbility().toString()));
        para.put(i++, new DbParameter(Types.INTEGER, data.getLevel()));
        para.put(i++, new DbParameter(Types.INTEGER, data.getStageLv()));
        para.put(i++, new DbParameter(Types.INTEGER, data.getBreakLv()));
        para.put(i++, new DbParameter(Types.INTEGER, data.getSkinId()));
        para.put(i++, new DbParameter(Types.INTEGER, data.getPromotionId()));
        if (getDb().executeNoneQuery(insertCrossChamberPatronsSql, para) > 0) {
            return true;
        }
        return false;
    }

    public boolean addCrossUnionNoticeList(List<CrossUnionNotice> dataList) {
        String sql = "INSERT INTO t_c_union_notice(unionUid,type,userId,nickName,noticeTime,content) VALUES (?,?,?,?,?,?)";
        try {
            getDb().setConnName(DbNameStrategy.getCross2Db());
            List<Map<Integer, DbParameter>> mapList = new ArrayList<>();
            for (CrossUnionNotice data : dataList) {
                Map<Integer, DbParameter> para = new HashMap<>();
                int i = 1;
                para.put(i++, new DbParameter(Types.VARCHAR, data.getUnionUid()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getType()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getUserId()));
                para.put(i++, new DbParameter(Types.VARCHAR, data.getNickName()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getNoticeTime()));
                para.put(i++, new DbParameter(Types.VARCHAR, data.getContent()));

                mapList.add(para);
            }
            return getDb().executeBatchQuery(sql, mapList) > -1;
        }catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        }
        return false;
    }

    public boolean addData(CrossUnionNotice data) {
        PreparedStatement call = null;
        String sql = "INSERT INTO t_c_union_notice(unionUid,type,userId,nickName,noticeTime,content) VALUES (?,?,?,?,?,?)";
        try {
            getDb().setConnName(DbNameStrategy.getCross2Db());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setString(i++, data.getUnionUid());
            call.setInt(i++, data.getType());
            call.setLong(i++, data.getUserId());
            call.setString(i++, data.getNickName());
            call.setLong(i++, data.getNoticeTime());
            call.setString(i++, data.getContent());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    public static String insertUnionFlagSql = "insert into t_c_union_flag(unionUid,flagId,expireTime,`read`) values (?,?,?,?)";
    public boolean addCrossUnionFlagList(List<CrossUnionFlag> dataList) {
        try {
            getDb().setConnName(DbNameStrategy.getCross2Db());
            List<Map<Integer, DbParameter>> mapList = new ArrayList<>();
            for (CrossUnionFlag data : dataList) {
                Map<Integer, DbParameter> para = new HashMap<>();
                int i = 1;
                para.put(i++, new DbParameter(Types.VARCHAR, data.getUnionUid()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getFlagId()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getExpireTime()));
                para.put(i++, new DbParameter(Types.BOOLEAN, data.isRead()));

                mapList.add(para);
            }
            return getDb().executeBatchQuery(insertUnionFlagSql, mapList) > -1;
        }catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        }
        return false;
    }
    public boolean addData(CrossUnionFlag unionFlag) {
        unionFlag.setBeginWriteTime();
        getDb().setConnName(DbNameStrategy.getCross2Db());
        int i = 1;
        Map<Integer, DbParameter> para = new HashMap<Integer, DbParameter>();
        para.put(i++, new DbParameter(Types.VARCHAR, unionFlag.getUnionUid()));
        para.put(i++, new DbParameter(Types.INTEGER, unionFlag.getFlagId()));
        para.put(i++, new DbParameter(Types.BIGINT, unionFlag.getExpireTime()));
        para.put(i++, new DbParameter(Types.BOOLEAN, unionFlag.isRead()));
        if (getDb().executeNoneQuery(insertUnionFlagSql, para) > 0) {
            return true;
        }
        return false;

    }

    public boolean addUnionTradeTeamDataList(List<UnionTradeTeamData> dataList) {
        String sql = "insert into t_c_union_trade_team(unionUid,routeId,openUser,openTime,startTradeTime,stateVal,finishType,sendReward,expectReward,reward,eventReward," +
                "logDataList,userJoinDataList,userReadList,eventTimeList,eventList,takeEventIndex,openNum,restTime,userInfoList) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        try {
            getDb().setConnName(DbNameStrategy.getCross2Db());
            List<Map<Integer, DbParameter>> mapList = new ArrayList<>();
            for (UnionTradeTeamData data : dataList) {
                Map<Integer, DbParameter> para = new HashMap<>();
                int i = 1;
                para.put(i++, new DbParameter(Types.VARCHAR, data.getUnionUid()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getRouteId()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getOpenUser()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getOpenTime()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getStartTradeTime()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getStateVal()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getFinishType()));
                para.put(i++, new DbParameter(Types.BOOLEAN, data.isSendReward()));
                para.put(i++, new DbParameter(Types.VARCHAR, data.getExpectReward()));
                para.put(i++, new DbParameter(Types.VARCHAR, data.getReward()));
                para.put(i++, new DbParameter(Types.VARCHAR, data.getEventReward()));
                para.put(i++, new DbParameter(Types.VARCHAR, JSONArray.toJSONString(data.getNewLogDataList())));
                para.put(i++, new DbParameter(Types.VARCHAR, JSONArray.toJSONString(data.getNewUserJoinDataList())));
                para.put(i++, new DbParameter(Types.VARCHAR, JSONArray.toJSONString(data.getNewUserReadList())));
                para.put(i++, new DbParameter(Types.VARCHAR, StringUtils.listToString(data.getEventTimeList(), ";")));
                para.put(i++, new DbParameter(Types.VARCHAR, StringUtils.listToString(data.getEventList(), ";")));
                para.put(i++, new DbParameter(Types.INTEGER, data.getTakeEventIndex()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getOpenNum()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getRestTime()));
                para.put(i++, new DbParameter(Types.VARCHAR, JSONArray.toJSONString(data.getNewUserInfoList())));

                mapList.add(para);
            }
            return getDb().executeBatchQuery(sql, mapList) > -1;
        }catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        }
        return false;
    }
    public boolean addData(UnionTradeTeamData data) {
        PreparedStatement call = null;
        String sql = "insert into t_c_union_trade_team(unionUid,routeId,openUser,openTime,startTradeTime,stateVal,finishType,sendReward,expectReward,reward,eventReward," +
                "logDataList,userJoinDataList,userReadList,eventTimeList,eventList,takeEventIndex,openNum,restTime,userInfoList) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        try {
            getDb().setConnName(DbNameStrategy.getCross2Db());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setString(i++, data.getUnionUid());
            call.setInt(i++, data.getRouteId());
            call.setLong(i++, data.getOpenUser());
            call.setLong(i++, data.getOpenTime());
            call.setLong(i++, data.getStartTradeTime());
            call.setInt(i++, data.getStateVal());
            call.setInt(i++, data.getFinishType());
            call.setBoolean(i++, data.isSendReward());
            call.setString(i++, data.getExpectReward());
            call.setString(i++, data.getReward());
            call.setString(i++, data.getEventReward());
            call.setString(i++, JSONArray.toJSONString(data.getNewLogDataList()));
            call.setString(i++, JSONArray.toJSONString(data.getNewUserJoinDataList()));
            call.setString(i++, JSONArray.toJSONString(data.getNewUserReadList()));
            call.setString(i++, StringUtils.listToString(data.getEventTimeList(), ";"));
            call.setString(i++, StringUtils.listToString(data.getEventList(), ";"));
            call.setInt(i++, data.getTakeEventIndex());
            call.setInt(i++, data.getOpenNum());
            call.setLong(i++, data.getRestTime());
            call.setString(i++, JSONArray.toJSONString(data.getNewUserInfoList()));
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    public boolean addUnionParergonList(List<UnionParergon> dataList) {
        String sql = "INSERT INTO t_c_union_parergon (unionId, parergonId, progress, parergonTimes, playerIds, dayRestoreTime) " +
                "VALUES (?, ?, ?, ?, ?, ?)";
        try {
            getDb().setConnName(DbNameStrategy.getCross2Db());
            List<Map<Integer, DbParameter>> mapList = new ArrayList<>();
            for (UnionParergon data : dataList) {
                Map<Integer, DbParameter> para = new HashMap<>();
                int i = 1;
                para.put(i++, new DbParameter(Types.VARCHAR, data.getUnionId()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getParergonId()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getProgress()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getParergonTimes()));
                para.put(i++, new DbParameter(Types.VARCHAR, data.getPlayerIds()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getDayRestoreTime()));

                mapList.add(para);
            }
            return getDb().executeBatchQuery(sql, mapList) > -1;
        }catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        }
        return false;
    }
    public boolean addData(UnionParergon data) {
        PreparedStatement call = null;
        String sql = "INSERT INTO t_c_union_parergon (unionId, parergonId, progress, parergonTimes, playerIds, dayRestoreTime) " +
                "VALUES (?, ?, ?, ?, ?, ?)";
        try {
            getDb().setConnName(DbNameStrategy.getCross2Db());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setString(i++, data.getUnionId());
            call.setInt(i++, data.getParergonId());
            call.setInt(i++, data.getProgress());
            call.setInt(i++, data.getParergonTimes());
            call.setString(i++, data.getPlayerIds());
            call.setLong(i++, data.getDayRestoreTime());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    public boolean addUnionParergonPlayerList(List<UnionParergonPlayer> dataList) {
        String sql = "INSERT INTO t_c_union_parergon_player (userId, operateTimes, lastRestoreTime, bargainTime, bargainUnionUId, todayTimes, totalTimes, historyTimes,dayUnionUId, dayRestoreTime) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        try {
            getDb().setConnName(DbNameStrategy.getCross2Db());
            List<Map<Integer, DbParameter>> mapList = new ArrayList<>();
            for (UnionParergonPlayer data : dataList) {
                Map<Integer, DbParameter> para = new HashMap<>();
                int i = 1;
                para.put(i++, new DbParameter(Types.BIGINT, data.getUserId()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getOperateTimes()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getLastRestoreTime()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getBargainTime()));
                para.put(i++, new DbParameter(Types.VARCHAR, data.getBargainUnionUId()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getTodayTimes()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getTotalTimes()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getHistoryTimes()));
                para.put(i++, new DbParameter(Types.VARCHAR, data.getDayUnionUId()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getDayRestoreTime()));

                mapList.add(para);
            }
            return getDb().executeBatchQuery(sql, mapList) > -1;
        }catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        }
        return false;
    }
    public boolean addData(UnionParergonPlayer data) {
        PreparedStatement call = null;
        String sql = "INSERT INTO t_c_union_parergon_player (userId, operateTimes, lastRestoreTime, bargainTime, bargainUnionUId, todayTimes, totalTimes, historyTimes,dayUnionUId, dayRestoreTime) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        try {
            getDb().setConnName(DbNameStrategy.getCross2Db());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setLong(i++, data.getUserId());
            call.setInt(i++, data.getOperateTimes());
            call.setLong(i++, data.getLastRestoreTime());
            call.setLong(i++, data.getBargainTime());
            call.setString(i++, data.getBargainUnionUId());
            call.setInt(i++, data.getTodayTimes());
            call.setInt(i++, data.getTotalTimes());
            call.setInt(i++, data.getHistoryTimes());
            call.setString(i++, data.getDayUnionUId());
            call.setLong(i++, data.getDayRestoreTime());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    public boolean addUnionBussinessmanList(List<UnionBussinessman> dataList) {
        String sql = "INSERT INTO t_c_union_bussinessman(bussinessId,unionId,disappearTime,productId,bargainPrice,bargainTimes,bargainNum," +
                "createTime,bargainValues) VALUES (?,?,?,?,?,?,?,?,?)";
        try {
            getDb().setConnName(DbNameStrategy.getCross2Db());
            List<Map<Integer, DbParameter>> mapList = new ArrayList<>();
            for (UnionBussinessman data : dataList) {
                Map<Integer, DbParameter> para = new HashMap<>();
                int i = 1;
                para.put(i++, new DbParameter(Types.INTEGER, data.getBussinessId()));
                para.put(i++, new DbParameter(Types.VARCHAR, data.getUnionId()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getDisappearTime()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getProductId()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getBargainPrice()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getBargainTimes()));
                para.put(i++, new DbParameter(Types.INTEGER, data.getBargainNum()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getCreateTime()));
                para.put(i++, new DbParameter(Types.VARCHAR, data.getBargainValuesStr()));

                mapList.add(para);
            }
            return getDb().executeBatchQuery(sql, mapList) > -1;
        }catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        }
        return false;
    }
    public boolean addData(UnionBussinessman data) {
        PreparedStatement call = null;
        String sql = "INSERT INTO t_c_union_bussinessman(bussinessId,unionId,disappearTime,productId,bargainPrice,bargainTimes,bargainNum," +
                "createTime,bargainValues) VALUES (?,?,?,?,?,?,?,?,?)";
        try {
            getDb().setConnName(DbNameStrategy.getCross2Db());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setInt(i++, data.getBussinessId());
            call.setString(i++, data.getUnionId());
            call.setLong(i++, data.getDisappearTime());
            call.setInt(i++, data.getProductId());
            call.setLong(i++, data.getBargainPrice());
            call.setInt(i++, data.getBargainTimes());
            call.setInt(i++, data.getBargainNum());
            call.setLong(i++, data.getCreateTime());
            call.setString(i++, data.getBargainValuesStr());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    public boolean addUnionBussinessmanDetailList(List<UnionBussinessmanDetail> dataList) {
        String sql = "INSERT INTO t_c_union_bussinessman_detail (bussinessId, userId, bargainPrice, bargainTime, hasBuy) VALUES (?, ?, ?, ?, ?)";
        try {
            getDb().setConnName(DbNameStrategy.getCross2Db());
            List<Map<Integer, DbParameter>> mapList = new ArrayList<>();
            for (UnionBussinessmanDetail data : dataList) {
                Map<Integer, DbParameter> para = new HashMap<>();
                int i = 1;
                para.put(i++, new DbParameter(Types.INTEGER, data.getBussinessId()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getUserId()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getBargainPrice()));
                para.put(i++, new DbParameter(Types.BIGINT, data.getBargainTime()));
                para.put(i++, new DbParameter(Types.BOOLEAN, data.isHasBuy()));

                mapList.add(para);
            }
            return getDb().executeBatchQuery(sql, mapList) > -1;
        }catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        }
        return false;
    }
    public boolean addData(UnionBussinessmanDetail data) {
        PreparedStatement call = null;
        String sql = "INSERT INTO t_c_union_bussinessman_detail (bussinessId, userId, bargainPrice, bargainTime, hasBuy) VALUES (?, ?, ?, ?, ?)";
        try {
            getDb().setConnName(DbNameStrategy.getCross2Db());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setInt(i++, data.getBussinessId());
            call.setLong(i++, data.getUserId());
            call.setLong(i++, data.getBargainPrice());
            call.setLong(i++, data.getBargainTime());
            call.setBoolean(i++, data.isHasBuy());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    public List<CrossUnionMember> getUnionMember(String unionUid) {
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "SELECT * FROM t_c_union_member";
        List<CrossUnionMember> memberList = new ArrayList<>();
        try {
            getDb().setConnName(DbNameStrategy.getCross2Db());
            call = getDb().getConnection().prepareCall(sql);
            rs = call.executeQuery();
            while (rs.next()) {
                CrossUnionMember data = new CrossUnionMember();
                data.setUnionUid(rs.getString("unionUid"));
                data.setUserId(rs.getLong("userId"));
                data.setPosition(rs.getInt("position"));
                String baseUserInfoStr = rs.getString("userBaseInfo");
                if (null == baseUserInfoStr) {
                    baseUserInfoStr = "";
                }
                UserBaseInfo userBaseInfo = JSON.parseObject(baseUserInfoStr, new TypeReference<UserBaseInfo>() {
                });
                if (null != userBaseInfo) {
                    data.setUserBaseInfo(userBaseInfo);
                }
                data.setModifyTime(rs.getLong("modifyTime"));
                data.setContribution(rs.getLong("contribution"));
                data.setTotalContribution(rs.getLong("totalContribution"));
                data.setDonateTimes(rs.getInt("donateTimes"));
                data.setQuitTime(rs.getLong("quitTime"));
                data.setTodayContribution(rs.getInt("todayContribution"));
                data.setChamberPatronsId(rs.getInt("chamberPatronsId"));
                data.setConstructRewardIndexList(StringUtils.stringToIntegerList(rs.getString("constructRewardIndexList"), ","));
                String unionConstructData = rs.getString("unionConstructData");
                Map<Integer, UnionConstruct> unionConstructMap = new ConcurrentHashMap<>();
                if (!StringUtils.isNullOrEmpty(unionConstructData)) {
                    unionConstructMap = JSON.parseObject(unionConstructData, new TypeReference<Map<Integer, UnionConstruct>>() {
                    });
                }
                data.setUnionConstructMap(unionConstructMap);
                data.setServerId(rs.getLong("serverId"));
                memberList.add(data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return memberList;
    }

    public boolean addUnionConditionData(UnionActivityConditionData data, CrossServerInfo serverInfo) {
        DbInfo dbInfo = serverInfo.getDbInfos().get(0);
        Connection conn = null;
        PreparedStatement call = null;
        String sql = "insert into t_c_union_activity_condition(unionUid,activityId,conditionId,preValue,value,isGetReward,lastUpdateTime,"
                + "memberList,info,unionBaseInfo,conditionType,positionInfo,extraValue) values (?,?,?,?,?,?,?,?,?,?,?,?,?)";
        try {
             conn = getConnect(dbInfo);
            call = conn.prepareStatement(sql);
            int i = 1;
            call.setString(i++, data.getUnionUid());
            call.setInt(i++, data.getActivityId());
            call.setInt(i++, data.getConditionId());
            call.setString(i++, data.getPreValue().toString());
            call.setString(i++, data.getValue().toString());
            call.setBoolean(i++, data.isGetReward());
            call.setLong(i++, data.getLastUpdateTime());
            call.setString(i++, StringUtils.listToString(data.getMemberUserIdList(), ","));
            call.setString(i++, data.getInfo());
            call.setString(i++, data.getUnionBaseInfoJsonStr());
            call.setInt(i++, data.getConditionType());
            call.setString(i++, data.getMemberPositionMapJsonStr());
            call.setString(i++, data.getExtraValue().toString());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            if (call != null) {
                try {
                    call.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    private Connection getConnect(DbInfo dbInfo) throws SQLException {
        String ip = dbInfo.getIp();
        int port = dbInfo.getPort();
        String userName = dbInfo.getUserName();
        String password = dbInfo.getPassword();
        Connection connection = DriverManager.getConnection("jdbc:mysql://" + dbInfo.getIp() + ":" + dbInfo.getPort() + "/" + dbInfo.getDbName() + "?useUnicode=true&character_set_server=utf8mb4&useSSL=false", dbInfo.getUserName(), dbInfo.getPassword());
        return connection;
    }

    public List<CrossServerInfo> getCrossActivityServerDb(int channelId) {
        ResultSet rs = null;
        CallableStatement call = null;
        List<CrossServerInfo> list = new ArrayList<>();
        String sql = "select * from t_s_cross_server_list";
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall(sql);
            rs = call.executeQuery();
            while (rs.next()) {
                CrossServerInfo crossServerInfo = new CrossServerInfo();
                int crossServerId = rs.getInt("crossServerId");
                crossServerInfo.setCrossServerId(rs.getInt("crossServerId"));
                DbInfo dbInfo = DbInfoParser.parseDbInfo(rs.getString("crossDatabase"));
                if (dbInfo != null) {
                    crossServerInfo.getDbInfos().add(dbInfo);
                }
                DbInfo configbase = DbInfoParser.parseDbInfo(rs.getString("crossConfigbase"));
                if (configbase != null) {
                    crossServerInfo.getDbInfos().add(configbase);
                }

                ProcessInfo crossProcessInfo = ProcessInfoParser.parsingProcessInfo(rs.getString("crossServerInfo"), crossServerId);
                ProcessInfo webServerInfo = ProcessInfoParser.parsingProcessInfo(rs.getString("webServerInfo"), crossServerId);
                crossServerInfo.getProcessInfoList().add(crossProcessInfo);
                crossServerInfo.getProcessInfoList().add(webServerInfo);
                crossServerInfo.setCrossServerType(rs.getInt("crossServerType"));
                list.add(crossServerInfo);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return list;
    }

    public void addUnionRank(LinkedList<CrossUnionActivityRank> rankList, CrossServerInfo serverInfo) {
        DbInfo dbInfo = serverInfo.getDbInfos().get(0);
        Connection conn = null;
        PreparedStatement call = null;
        String sql = "REPLACE INTO t_c_union_activity_rank(serverId,activityId,rank,unionUid,unionBaseInfo,value,lastUpdateTime,isDel) VALUES(?,?,?,?,?,?,?,?)";
        try {
            conn = getConnect(dbInfo);
            call = conn.prepareStatement(sql);
            int rank = 1;
            for (CrossUnionActivityRank unionRank : rankList) {
                int i = 1;
                call.setLong(i++, unionRank.getUnionBaseInfo().getServerId());
                call.setInt(i++, unionRank.getActivityId());
                call.setInt(i++, rank);
                call.setString(i++, unionRank.getUnionUid());
                call.setString(i++, unionRank.getUnionBaseInfoJsonStr());
                call.setString(i++, unionRank.getValue().toString());
                call.setLong(i++, unionRank.getLastUpdateTime());
                call.setBoolean(i++, unionRank.isDel());
                rank++;
                call.executeUpdate();
            }
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            if (call != null) {
                try {
                    call.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
